#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys, string
import poplib
import os
import time
import datetime
from email.parser import Parser
# 用来解析邮件主题
from email.header import decode_header
# 用来解析邮件来源
from email.utils import parseaddr
import platform
from tqdm import tqdm

class ark_email_spider():
    def parser_subject(self,msg):
        subject = msg['Subject']
        value, charset = decode_header(subject)[0]
        if charset:
            value = value.decode(charset)
        # print('邮件主题value=',value)
        return value

    def parser_address(self,msg):
        hdr, addr = parseaddr(msg['From'])
        # name 发送人邮箱名称， addr 发送人邮箱地址
        name, charset = decode_header(hdr)[0]
        if charset:
            name = name.decode(charset)
        # print('发送人邮箱名称name=',name,'发送人邮箱地址addr=',addr)
        return name,addr

    def get_all_email_content(self,today_date_str):
        useraccount = 'tradego_ark'
        password = 'ISAQTMOLGMMNYRSC'

        # 邮件服务器地址,以下为网易邮箱
        pop3_server = 'pop.163.com'

        # 开始连接到服务器
        server = poplib.POP3(pop3_server)

        # 打开或者关闭调试信息，为打开，会在控制台打印客户端与服务器的交互信息
        server.set_debuglevel(1)


        # 开始进行身份验证
        server.user(useraccount)
        server.pass_(password)

        # 返回邮件总数目和占用服务器的空间大小（字节数）， 通过stat()方法即可
        email_num, email_size = server.stat()
        # print('消息的数量email_num=',email_num,'消息的总大小email_size=',email_size)

        # 使用list()返回所有邮件的编号，默认为字节类型的串
        rsp, msg_list, rsp_siz = server.list()
        # print('服务器的响应rsp=',rsp,'消息列表msg_list=',msg_list,'返回消息的大小rsp_siz=',rsp_siz)

        flag = False

        # print('邮件总数len(msg_list)=',len(msg_list))
        for i in range(1,len(msg_list)+1):
            rsp, msglines, msgsiz = server.retr(i)

            msg_content = b'\n'.join(msglines).decode('utf-8')
            msg_content = msg_content.replace('=\n', '')

            new_msg = Parser().parsestr(text=msg_content)

            msg_date = new_msg['Date']

            # 邮件主题
            subject_value = self.parser_subject(new_msg)
            if isinstance(subject_value, bytes):
                subject_value = subject_value.decode('utf-8')
            name, addr = self.parser_address(new_msg)

            if name == 'ARK Trading Desk' and addr == 'ark@ark-funds.com' and 'ARK Investment Management LLC' in subject_value:
                BJS_msg_date = self.UTC2BJS(msg_date)
                if today_date_str==BJS_msg_date:
                    flag=True
                    break

        # 关闭与服务器的连接，释放资源
        server.close()

        return flag

    # ===UTC2BJS
    @staticmethod
    def UTC2BJS(UTC):
        UTC_format = "%a, %d %b %Y %H:%M:%S %z (UTC)"
        # BJS_format = "%Y-%m-%d %H:%M:%S"
        BJS_format = "%Y-%m-%d"
        UTC = datetime.datetime.strptime(UTC, UTC_format)
        # 格林威治时间+8小时变为北京时间
        BJS = UTC + datetime.timedelta(hours=8)
        BJS = BJS.strftime(BJS_format)
        return BJS

if __name__=='__main__':
    # 范围时间
    start_8 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '8:00', '%Y-%m-%d%H:%M')
    end_8 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '8:10', '%Y-%m-%d%H:%M')

    start_9 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:00', '%Y-%m-%d%H:%M')
    end_9 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:10', '%Y-%m-%d%H:%M')

    start_10 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '10:00', '%Y-%m-%d%H:%M')
    end_10 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '10:10', '%Y-%m-%d%H:%M')

    start_11 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '11:00', '%Y-%m-%d%H:%M')
    end_11 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '11:10', '%Y-%m-%d%H:%M')

    start_12 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '12:00', '%Y-%m-%d%H:%M')
    end_12 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '12:10', '%Y-%m-%d%H:%M')

    start_test = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '16:44', '%Y-%m-%d%H:%M')
    end_test = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '16:46', '%Y-%m-%d%H:%M')

    while True:
        today_weekday = datetime.datetime.now().weekday() + 1
        if today_weekday != 1 and today_weekday != 7:
            print('今天周', today_weekday, '需要运行程序...')
            # 当前时间
            n_time = datetime.datetime.now()
            # print(n_time)
            if (n_time > start_8 and n_time < end_8) or (n_time > start_9 and n_time < end_9) or (
                    n_time > start_10 and n_time < end_10) \
                    or (n_time > start_11 and n_time < end_11) or (n_time > start_12 and n_time < end_12):
                print(n_time, '在定时任务时间内，不用运行...')
                print(datetime.datetime.now(), '休眠5分钟...')
                for i in tqdm(range(300), ncols=50):
                    time.sleep(1)
            else:
                print(n_time, 'ArkSpider程序需要执行,正在执行...', )
                ark_e = ark_email_spider()
                today_date = datetime.datetime.now().date()
                today_date_str = str(today_date)

                # 获取最新一封邮件，查看是不是今天的ARK新邮件
                flag = ark_e.get_all_email_content(today_date_str=today_date_str)
                if flag:
                    if platform.system().lower() == 'windows':
                        os.system('python main_run.py')
                    elif platform.system().lower() == 'linux':
                        os.system('sh run.sh')
                    print(datetime.datetime.now(), 'main_run.py运行完毕...')
                else:
                    print(datetime.datetime.now(), '本次没有新邮件，不用运行...')
                print(datetime.datetime.now(), '休眠5分钟...')
                for i in tqdm(range(300), ncols=50):
                    time.sleep(1)
            print(datetime.datetime.now(), '运行一次结束...')
        else:
            print('今天周', today_weekday, '不需要运行程序...')



